package com.mylibraryapplication.http;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;

import com.mylibrary.util.AbStrUtil;
import com.mylibraryapplication.http.HException.ApiException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

//import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * Description: 自定义Subscribe
 */
public abstract class RxSubscribe<T> extends Subscriber<T> {
    private Context mContext;
    private ProgressDialog dialog;
    private String msg;
    private final String TAG=this.getClass().getSimpleName();

    protected boolean showDialog() {
        return true;
    }

    /**
     * @param context context
     * @param msg     dialog message
     */
    public RxSubscribe(Context context, String msg) {
        this.mContext = context;
        this.msg = msg;
    }

    /**
     * @param context context
     */
    public RxSubscribe(Context context) {
        this(context, "请稍后...");
    }

    @Override
    public void onCompleted() {
        if (showDialog())
            dialog.dismiss();
        Log.e(TAG,"加载完成");
    }
    @Override
    public void onStart() {
        super.onStart();
        Log.e(TAG,"开始加载");
        if (showDialog()) {
            dialog = new ProgressDialog(mContext, ProgressDialog.STYLE_HORIZONTAL);
            dialog.setMessage(msg);
            dialog.setCancelable(true);
            dialog.setCanceledOnTouchOutside(true);
            //点击取消的时候取消订阅
            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if(!isUnsubscribed()){
                        unsubscribe();
                    }
                }
            });
            dialog.show();
        }
    }
    @Override
    public void onNext(T t) {
        _onNext(t);
    }
    //对应HTTP的状态码
    private static final int UNAUTHORIZED = 401;
    private static final int FORBIDDEN = 403;
    private static final int NOT_FOUND = 404;
    private static final int REQUEST_TIMEOUT = 408;
    private static final int INTERNAL_SERVER_ERROR = 500;
    private static final int BAD_GATEWAY = 502;
    private static final int SERVICE_UNAVAILABLE = 503;
    private static final int GATEWAY_TIMEOUT = 504;

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        HttpException httpException = (HttpException) e;
        int resultCode=httpException.code();
        Log.e(TAG,httpException.code()+"====网络请求失败==="+e.getMessage());
        ApiException ex = new ApiException(e, httpException.code());
        String errorMessage;

        if(resultCode==UNAUTHORIZED){
            errorMessage="请求"+UNAUTHORIZED;
            ex.setDisplayMessage("请求"+UNAUTHORIZED);
        }else if(resultCode==FORBIDDEN){
//            onPermissionError(ex);          //权限错误，需要实现\
            errorMessage="权限错误";
            ex.setDisplayMessage("权限错误");
        }else if(resultCode==NOT_FOUND){
            ex.setDisplayMessage("访问页面失败404");
            errorMessage="访问页面失败404";
        }else if(resultCode==REQUEST_TIMEOUT){
            ex.setDisplayMessage("请求"+REQUEST_TIMEOUT);
            errorMessage="请求"+REQUEST_TIMEOUT;
        }else if(resultCode==GATEWAY_TIMEOUT){
            ex.setDisplayMessage("请求超时"+GATEWAY_TIMEOUT);
            errorMessage="请求超时"+GATEWAY_TIMEOUT;
        }else if(resultCode==INTERNAL_SERVER_ERROR){
            ex.setDisplayMessage("请求"+INTERNAL_SERVER_ERROR);
            errorMessage="请求"+INTERNAL_SERVER_ERROR;
        }else if(resultCode==BAD_GATEWAY){
            ex.setDisplayMessage("请求"+BAD_GATEWAY);
            errorMessage="服务器错误";
        }else if(resultCode==SERVICE_UNAVAILABLE){
            ex.setDisplayMessage("请求"+SERVICE_UNAVAILABLE);
            errorMessage="请求"+SERVICE_UNAVAILABLE;
        }else{
            errorMessage="网络错误";
            ex.setDisplayMessage("网络错误");  //均视为网络错误
            onError(ex);
        }
        if(!AbStrUtil.isEmpty(errorMessage)){
            _onError(errorMessage,httpException.code());
        }

//        if (false) { //这里自行替换判断网络的代码
//            _onError("网络不可用");
//        } else if (e instanceof ServerException) {
//            _onError(e.getMessage());
//
//        } else {
//            _onError("请求失败，请稍后再试...");
//        }
        if (showDialog())
            dialog.dismiss();
    }

    protected abstract void _onNext(T t);

    protected abstract void _onError(String message,int code);

}
